package com.ihrm.common.interceptor;

import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 小伟
 * @version V1.0
 * @Package com.ihrm.common.interceptor
 * @date 2020/12/16 22:50
 * @Copyright © 2020-2021 郑州恒星科技有限责任公司
 * jwt 自定义拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.hasLength(authorization) && authorization.startsWith("Bearer")) {
            String token = authorization.replace("Bearer ", "");
            Claims claims = jwtUtils.parseJwtToken(token);
            if (claims != null) {
                //从token中获取用户级别
                String level = (String) claims.get("user_level");
                //判断是否为管理员，是则直接放行
                if (level.equals("saasAdmin") || level.equals("coAdmin")) {
                    request.setAttribute("claims", claims);
                    return true;
                }
                //从token中获取用户权限标识
                String apis = (String) claims.get("user_apis");
                //从request中获取当前用户要访问的api接口名
                HandlerMethod method = (HandlerMethod) handler;
                RequestMapping annotation = method.getMethodAnnotation(RequestMapping.class);
                String name = annotation.name();
                if (apis.contains(name)) {
                    request.setAttribute("claims", claims);
                    return true;
                } else {
                    throw new CommonException(ResultCode.UNAUTHORISE);
                }
            }
        }
        throw new CommonException(ResultCode.UNAUTHENTICATED);
    }
}
